package com.ysyc.driver_ee.api;


import android.app.Dialog;
import android.content.Intent;

import com.ysyc.driver_ee.tools.ToastUtils;

import java.util.AbstractMap;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @program: YSYC_Customer
 * @description: ${description}
 * @author: Mr.CHAN
 * @create: 2018-08-24 11:51
 **/
public class NetworkCallback<T> {

    public HttpResource<T> resource;

    public Disposable disposable;

    public static final String SESSION_KEY_NOT_FOUND = "123";
    public static final String SESSION_KEY_FOUND = "124";


    public NetworkCallback(HttpResource<T> resource) {
        this.resource = resource;
    }


    public void postRequest(Observable<T> observable, Dialog dialog) {
        resource.onLoading(dialog);
        observable.subscribeOn(Schedulers.io())        //在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  //回到主线程去处理请求结果
                .subscribe(new Observer<T>() {

                    private Intent intent;

                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(T value) {
                        onDestroy();
                        if (value instanceof ApiException) {
                            ApiException apiException = (ApiException) value;
                            Integer code = ((ApiException) value).code;
                            String msg = ((ApiException) value).msg;
//                            if (SESSION_KEY_NOT_FOUND.equals(code)||SESSION_KEY_FOUND.equals(code)) {
//                                EventBus.getDefault().post(new BaseEvent(msg));
//                            }

                            resource.onFailure(apiException.getMsg());


                        } else {
                            resource.onSuccess(value);


                        }
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        onDestroy();
                        ToastUtils.show("网络状态异常,请稍后再试");
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onComplete() {
                        onDestroy();
                    }
                });


    }

    public void onDestroy() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
